<?php
declare (strict_types=1);

namespace app\index\controller;

use app\common\controller\Frontend;
use app\common\model\Order as OrderModel;
use app\common\model\Room as RoomModel;
use think\Request;


class Order extends Frontend
{
    //订单列表
    public function index(Request $request)
    {
        $page = $request->get("page", 1) ?: 1;
        $userId = session('user.id');

        $roomList = RoomModel::select()->toArray();
        $orderList = OrderModel::where('user_id', $userId)->select()->toArray();
        $roomMap = array_column($roomList, 'name', 'id');
        foreach ($orderList as &$order) {
            $order['room_name'] = $roomMap[$order['room_id']] ?? '';
            if ($order['status'] == 1) {
                $order['status_str'] = '已预订';
            } else if ($order['status'] == 2) {
                $order['status_str'] = '退房审核中';
            } else if ($order['status'] == 3) {
                $order['status_str'] = '已取消';
            } else if ($order['status'] == 4) {
                $order['status_str'] = '入住中';
            } else if ($order['status'] == 5) {
                $order['status_str'] = '已退房';
            }
        }

        //分页数据
        $size = 10;
        $total = count($orderList);
        $totalPage = ceil(count($orderList) / $size);
        $orderList = array_slice($orderList, ($page - 1) * $size, $size);

        return view('order/index', [
            'orderList' => $orderList,
            'total' => $total,
            'totalPage' => $totalPage,
            'page' => $page
        ]);
    }

    //退房申请
    public function cancel($id) {
        OrderModel::where(['id' => $id])->update(['status' => 2]);
        $this->redirect('/order/index');
    }

    //保存订单
    public function save(Request $request) {
        $data = $request->post();

        $roomId = $data['room_id'];
        $roomNumber = $data['room_number'];
        //忽略已取消订单
        $orders = OrderModel::where('room_id', $roomId)->where('room_number', $roomNumber)
            ->whereIn('status', [1, 2])->select()->toArray();
        //客房已被预定的日期
        $orderDays = [];
        foreach ($orders as $order) {
            $orderDays += get_interval_dates($order['start_date'], $order['end_date']);
        }

        //当前订单需要预定日期
        $currentDays = get_interval_dates($data['start_date'], $data['end_date']);
        //日期取交集
        $intersectDays = array_intersect($orderDays, $currentDays);

        if (!empty($intersectDays)) {
            $intersectDaysStr = implode(",", $intersectDays);
            $this->error("预定失败:" . $intersectDaysStr . "已被预定" , "/room/reserve?id=" . $roomId);
        }

        $days = date_diff(date_create($data['start_date']), date_create($data['end_date']))->days;
        $data['order_no'] = date("Ymd") . time() . rand(10, 99);
        $data['days'] = $days;
        $data['total'] = $days * $data['price'];
        $data['status'] = 1;   //初始状态 1已预订
        $data['user_id'] = session('user.id');
        OrderModel::create($data);
        $this->success("预定成功", "/order");
    }
}
